const { db, query } = require("../../db/db");
const util = require("util");

async function GetArticleCommentList(req, res) {
  const ArticleId = req.body.ArticleId;
  let PageSize = req.body.PageSize;
  let PageNum = req.body.PageNum;

  if (!PageSize) {
    PageSize = 10;
  }
  if (!PageNum) {
    PageNum = 1;
  }

  const select_Father_comment_sql = util.format(
    "Select \
    Comment.CommentId, \
    Comment.CreateUserId,\
    IFNULL(Comment.CommentContent,'') as CommentContent, \
    IFNULL(Comment.CreateTime,'') as CreateTime, \
    IFNULL(User.HeaderImg,'') as HeaderImg, \
    IFNULL(User.UserName,'') as CommentUserName, \
    Comment.LikeNum, \
    Comment.ArticleId \
    From Comment LEFT JOIN User\
    ON Comment.CreateUserId=User.UserId\
    Where Comment.FatherCommentId IS  NULL AND Comment.ArticleId=%s ORDER BY Comment.CreateTime Desc",
    ArticleId
    /* (PageNum - 1) * PageSize,
    PageSize */
  );

  const select_Father_comment_sql_res = await query(select_Father_comment_sql);

  console.log("111111", select_Father_comment_sql_res);

  let CommentFuList = select_Father_comment_sql_res;

  for (let i = 0; i < select_Father_comment_sql_res.length; i++) {
    const Select_FId_children_sql = util.format(
      "Select  \
      c.CreateUserId,\
      c.CommentId,\
      c.AtUserId,\
      IFNULL(c.CommentContent,'') as CommentContent, \
      IFNULL(c.LikeNum,0) as LikeNum, \
    IFNULL(c.CreateTime,'') as CreateTime, \
    IFNULL(u1.HeaderImg,'') as HeaderImg, \
    IFNULL(u1.UserName,'') as CommentUserName, \
    IFNULL(u2.UserName,'') as AtUserName\
    From Comment c Left Join User u1 ON\
    c.CreateUserId=u1.UserId LEFT JOIN User u2 ON\
    c.AtUserId=u2.UserId\
    Where c.FatherCommentId=%s",
      select_Father_comment_sql_res[i].CommentId
    );
    const Select_FId_children_sql_res = await query(Select_FId_children_sql);
    if (Select_FId_children_sql_res[0]) {
      CommentFuList[i].Children = Select_FId_children_sql_res;
    } else {
      CommentFuList[i].Children = [];
    }
  }
  res.send({
    status: 0,
    CommentList: CommentFuList,
  });
}

module.exports = { GetArticleCommentList };
